<?php
/**
 *
* Copyright(c) 201x,
* All rights reserved.
*
* 功 能：mysql 存储日志
* @author cabing_2005@126.com
* @date 2014-8-13
* 版 本：1.0
 */
require_once "dispose.interface.php";
require_once dirname(dirname(__FILE__))."/service.conf.php";
class DbHandle
{
    public static $m_instance = array();
    //获取句柄
    public static function getInstance($db_config=array())
    {
        if(empty($db_config))
        {
            throw new DbHandleException("please check the db config!");
        }
        if(!isset($db_config["host"]) || !isset($db_config["user"]) || !isset($db_config["password"]) || !isset($db_config["db"]))
        {
            throw new DbHandleException("the config file like this array(host,user,password)");
        }

        $host = $db_config["host"];
        $user = $db_config["user"];
        $password = $db_config["password"];
        $db = $db_config["db"];

        $db_key = md5($host.$user.$password.$db);

        if (!array_key_exists($db_key,self::$m_instance))
        {
            self::$m_instance[$db_key] = mysql_connect($host,$user,$password);
            mysql_select_db($db,self::$m_instance[$db_key]);
            mysql_query("set names utf8",self::$m_instance[$db_key]);

        }
        return self::$m_instance[$db_key];
    }
    //查询
    public static function query($sql,$handle)
    {
        return mysql_query($sql,$handle);
    }
}
class DbHandleException extends Exception{}
/**
 * 存储mysql 日志
 */
class MysqlDispose extends DbHandle implements Dispose {

    const LOG_TYPE = "log";
    const LOG_TABLE = "log_service_";

    public static function  dispose($params)
    {
        if(!isset($GLOBALS["DB_CONFIG"][self::LOG_TYPE]))
        {
            throw new MysqlDisposeException("dbconfig faild");
        }else{
            $config = $GLOBALS["DB_CONFIG"][self::LOG_TYPE];
        }
        if(!is_string($params)){
            throw new MysqlDisposeException("params faild ".__LINE__);
        }
        $sql = "insert into ".self::getTable().$params;
        $handle = self::getInstance($config);
        self::query($sql, $handle);
    }
    /**
     * todo 分表
     */
    public static function getTable()
    {
        return self::LOG_TABLE."1";
    }

}
class MysqlDisposeException extends Exception{}







